package kpi.javatraining6.gnatiuk.src.teachingsystem;


import kpi.javatraining6.gnatiuk.src.tester.Questionnaire;
import kpi.javatraining6.gnatiuk.src.tester.question.Question;
import kpi.javatraining6.gnatiuk.src.tester.question.QuestionWithTopic;
import kpi.javatraining6.gnatiuk.src.tester.readers.QuestionsSAXParser;

import java.io.File;
import java.nio.file.NoSuchFileException;
import java.util.*;

public class TopicCombiner {
    public Map<String, Questionnaire> getQuestionnaires() throws NoSuchFileException {
        ArrayList<String> topicNames = getFiles();
        Map<String, Questionnaire> resultMap = new HashMap<>(topicNames.size());
        QuestionsSAXParser questionsParser = new QuestionsSAXParser();
        for (String topicName: topicNames) {
            String topicTitle = topicName.replace(".xml", "");
            List<Question> questionWithTopics = decorateWithTopics(questionsParser.parse(topicName), topicTitle);
            resultMap.put(topicTitle, new Questionnaire(questionWithTopics));
        }
        return resultMap;
    }

    private List<Question> decorateWithTopics(List<Question> questions, String topicName) {
        Question question;
         for (int i = 0; i < questions.size(); i++) {
             question = new QuestionWithTopic(questions.get(i), topicName);
             questions.set(i, question);
         }
        return questions;
    }

    private ArrayList<String> getFiles(){
        String QUESTIONS_FILE_EXTENSION = ".xml";
        String QUESTIONS_PATH = "src/kpi/javatraining6/gnatiuk/src/questionnairs/";
        File dir=new File(QUESTIONS_PATH);
        if(dir.isDirectory()){
            ArrayList<String> questionFiles = new ArrayList<>();
            for (String file : dir.list()) {
                if(file.endsWith(QUESTIONS_FILE_EXTENSION)){
                    questionFiles.add(file);
                }
            }
            return questionFiles;
        }else{
            throw new NoSuchElementException();
        }
    }
}
